/**
 *入职指引
 */
import React, { useEffect, useMemo, useRef, useState } from 'react';

import { Spin } from 'antd';
import { Modal, Steps, Toast, WhiteSpace } from 'antd-mobile';
import { size } from 'lodash';
import { createForm } from 'rc-form';
import { Link, router, withRouter } from 'umi';

import IconPro from '@/components/IconPro';
import { defaultFormatResult, useRequest } from '@/hooks';
import StepNotice from '@/pages/EntryManage/mobile/EntryGuide/components/StepNotice/StepNotice';
import { getFirstSimpleInfo, insertDevice, saveMaterials } from '@/pages/EntryManage/services';
import { printScreenDown } from '@/pages/EntryManage/utils';
import { Button } from '@/pages/Recruitment/External/components';
import { toArray } from '@/utils/utils';

import xss from 'xss';
import EntryMetaTag from '../components/EntryMetaTag';
import Logo from '../components/Logo';
import StepMaterials from './components/StepMaterials';
import StepUserInfoMobile from './components/StepUserInfo';
import styles from './index.less';

const { Step } = Steps;

const EntryGuideMobile = ({ entryPersonnelCode, location }) => {
    const { query } = location;
    const [currentStep, setCurrentStep] = useState(-1);
    const [uploadIng, setUploadIng] = useState();
    const step1Ref = useRef();
    const step2Ref = useRef();

    const step2Info = localStorage.getItem('step2InfoData') ? JSON.parse(localStorage.getItem('step2InfoData')) : {};

    const handleScrollTop = () => {
        document.getElementById('entryGuideAnchor').scrollIntoView();
    };

    // 获取入职人员信息
    const { data: entryPersonnelData = {}, run: runGetFirstSimpleInfo, loading } = useRequest(
        () => getFirstSimpleInfo({ entryPersonnelCode }),
        {
            ready: !!entryPersonnelCode,
            ...defaultFormatResult
        }
    );
    // 根据步骤渲染
    const renderStep = useMemo(() => {
        switch (currentStep) {
            case 0:
                return <StepUserInfoMobile wrappedComponentRef={step1Ref} entryPersonnelData={entryPersonnelData} />;
            case 1:
                return (
                    <StepMaterials
                        setUploadIng={setUploadIng}
                        wrappedComponentRef={step2Ref}
                        entryPersonnelData={{ ...entryPersonnelData, ...step2Info }}
                    />
                );
            case 2:
                return <StepNotice entryPersonnelData={entryPersonnelData} />;
            default:
                return null;
        }
    }, [currentStep, entryPersonnelData, step2Info]);

    // 简单判断是否登录
    useEffect(() => {
        if (!entryPersonnelCode) {
            history.push({
                pathname: '/recruitment/login',
                query: {
                    id: query.id
                }
            });
        } else if (entryPersonnelData) {
            // 根据接口显示步骤
            setCurrentStep(entryPersonnelData?.step === 2 ? 2 : 0);
        }
    }, [entryPersonnelCode, entryPersonnelData, query]);

    const [entryTimeModalVisible, setEntryTimeModalVisible] = useState(false);
    const renderChangeEntryDate =
        entryPersonnelData?.entryStatus <= 5 ? (
            <div style={{ marginBottom: 10 }}>
                {!entryPersonnelData?.applyEntryDateStatus && (
                    <>
                        请您在 {entryPersonnelData.entryDate} 至公司入职&emsp;
                        <Link
                            to={`/blank/entryManage/entryGuide/changeEntryDate?entryPersonnelCode=${entryPersonnelCode}`}
                        >
                            <IconPro type="edit" /> 修改
                        </Link>
                    </>
                )}
                {entryPersonnelData?.applyEntryDateStatus === 'waitfor' && (
                    <>
                        您的
                        <span style={{ color: '#FFA22D' }} onClick={() => setEntryTimeModalVisible(true)}>
                            入职时间待定
                        </span>
                        ，请等待HR与您联系确认
                        <Modal
                            visible={entryTimeModalVisible}
                            transparent
                            maskClosable={false}
                            title="入职时间待定"
                            footer={[{ text: '我知道了', onPress: () => setEntryTimeModalVisible(false) }]}
                        >
                            <div style={{ maxHeight: 200, overflow: 'auto' }}>
                                <table className={styles.entryTimeModal}>
                                    <tbody>
                                        <tr>
                                            <td>原入职时间：</td>
                                            <td>{entryPersonnelData?.entryDate}</td>
                                        </tr>
                                        <tr>
                                            <td>期望入职时间：</td>
                                            <td>{entryPersonnelData?.applyEntryDate}</td>
                                        </tr>
                                        <tr>
                                            <td style={{ verticalAlign: 'top' }}>修改原因：</td>
                                            <td>
                                                <div
                                                    style={{ wordBreak: 'break-all', display: 'inline' }}
                                                    // eslint-disable-next-line react/no-danger
                                                    dangerouslySetInnerHTML={{
                                                        __html: xss(
                                                            entryPersonnelData?.applyEntryDateReason?.replace(
                                                                /\s+/g,
                                                                '<br>'
                                                            )
                                                        )
                                                    }}
                                                />
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </Modal>
                    </>
                )}
                {entryPersonnelData?.applyEntryDateStatus === 'finished' &&
                    `请您在 ${entryPersonnelData.entryDate} 至公司入职`}
            </div>
        ) : null;

    // 步骤条
    const stepsMap = [
        {
            title: '信息确认',
            intro: (
                <div>
                    {renderChangeEntryDate}
                    为了确保顺利入职体验，我们已经开始相关准备工作！ <br />
                    进一步核对、完善个人档案资料，有利于我们更好的了解您！
                </div>
            )
        },
        {
            title: '材料提供',
            intro: (
                <>
                    {renderChangeEntryDate}
                    <div className={styles.step2Intro}>
                        {/* <i className={styles.line} /> */}
                        为了确保顺利入职，请提前准备相关入职材料哦！
                        {/* <i className={styles.line} /> */}
                    </div>
                </>
            )
        },
        {
            title: '入职须知',
            intro: renderChangeEntryDate
        }
    ];

    // 第一步信息确认提交
    const { loading: step1Loading, run: runInsertDevice } = useRequest(param => insertDevice(param), {
        manual: true,
        onSuccess: ({ msg, code }) => {
            if (code === 10000) {
                Toast.success(msg, 3, null, false);
                setCurrentStep(1);
                handleScrollTop();
            } else {
                Toast.fail(msg);
            }
        }
    });

    // 第二步信息确认提交
    const { loading: step2Loading, run: runSaveMaterials } = useRequest(param => saveMaterials(param), {
        manual: true,
        onSuccess: ({ msg, code }) => {
            if (code === 10000) {
                Toast.success(msg, 3, null, false);
                setCurrentStep(2);
                handleScrollTop();
                // 清除系统登录信息，防止登录信息冲突
                localStorage.removeItem('user');
                localStorage.removeItem('step2InfoData');
            } else {
                Toast.fail(msg);
            }
        }
    });

    const step2GoBack = () => {
        const { form } = step2Ref.current;
        localStorage.setItem('step2InfoData', JSON.stringify(form.getFieldsValue()));
    };

    const renderStepButton = useMemo(() => {
        switch (currentStep) {
            case 0:
                return (
                    <div className={styles.stepBtn}>
                        <Button
                            type="primary"
                            loading={step1Loading}
                            onClick={() => {
                                const { form } = step1Ref.current;
                                if (form) {
                                    form.validateFields((err, values) => {
                                        if (!err) {
                                            const param = {
                                                entryPersonnelCode,
                                                ...values,
                                                idPhoto: values?.idPhoto?.uploadResourceFile
                                                    ? [values?.idPhoto?.uploadResourceFile]
                                                    : []
                                            };
                                            runInsertDevice(param);
                                        } else {
                                            const tempList = Object.values(err);
                                            if (tempList && tempList.length > 0) {
                                                const { errors } = tempList[0];
                                                Toast.info(errors[0]?.message, 3, null, false);
                                            }
                                        }
                                    });
                                }
                            }}
                        >
                            下一步
                        </Button>
                    </div>
                );
            case 1:
                return (
                    <div className="formControls">
                        <Button
                            style={{ marginRight: 24 }}
                            onClick={() => {
                                step2GoBack();
                                runGetFirstSimpleInfo();
                                setCurrentStep(0);
                                handleScrollTop();
                            }}
                        >
                            上一步
                        </Button>
                        <Button
                            loading={step2Loading}
                            disabled={uploadIng}
                            type="primary"
                            onClick={() => {
                                const { form } = step2Ref.current;
                                if (form) {
                                    form.validateFields((err, values) => {
                                        const { materialsConfigData = {} } = step2Ref.current;
                                        if (!err) {
                                            const {
                                                electronMaterials = [],
                                                entityMaterials = []
                                            } = materialsConfigData;

                                            // 处理返回给后端的数据结构
                                            const materials = Object.entries(values).map(item => {
                                                // 分开是为了添加一个所属分组
                                                const electronArr = electronMaterials.filter(
                                                    subItem => subItem?.materialCode === item[0]
                                                );
                                                const entityArr = entityMaterials.filter(
                                                    subItem => subItem?.materialCode === item[0]
                                                );
                                                // 添加group区分分组！
                                                const materialDesc =
                                                    size(electronArr) > 0
                                                        ? { ...electronArr[0], group: 0 }
                                                        : { ...entityArr[0], group: 1 };

                                                return {
                                                    materialCode: item[0],
                                                    // 后端要求转字符串
                                                    materialValue:
                                                        typeof item[1] === 'object'
                                                            ? JSON.stringify(toArray(item[1]?.uploadResourceFile))
                                                            : item[1],
                                                    materialDesc
                                                };
                                            });
                                            const param = {
                                                entryPersonnelCode,
                                                materials
                                            };
                                            runSaveMaterials(param);
                                        } else {
                                            const tempList = Object.values(err);
                                            if (tempList && tempList.length > 0) {
                                                const { errors } = tempList[0];
                                                Toast.info(errors[0]?.message, 3, null, false);
                                            }
                                        }
                                    });
                                }
                            }}
                        >
                            提交
                        </Button>
                    </div>
                );
            case 2:
                return (
                    <div className="formControls">
                        <Button
                            type="primary"
                            onClick={() => {
                                printScreenDown(document.querySelector('#entryGuideWrap'), '入职须知');
                            }}
                        >
                            下载入职须知
                        </Button>
                    </div>
                );
            default:
                return null;
        }
    }, [
        currentStep,
        entryPersonnelCode,
        runGetFirstSimpleInfo,
        runInsertDevice,
        runSaveMaterials,
        step1Loading,
        step2Loading,
        uploadIng
    ]);

    // 用于下载的时候dom 为了避免下载的时候出现手机截屏兼容做的
    const copyDownDom = () => (
        <div
            id="entryGuideWrap"
            style={{
                position: 'fixed',
                right: '1000px',
                width: '100%',
                top: 0
            }}
        >
            <div style={{ backgroundColor: '#fff' }} id="entryGuideAnchor">
                <Logo />
                <p className={styles.name}>{entryPersonnelData.employeeName} 你好！</p>
                <h3 className={styles.title} style={{ marginBottom: 0 }}>
                    请根据指引完成入职准备
                </h3>
            </div>
            <div>
                {stepsMap[currentStep]?.intro && (
                    <div data-hideinprint="true">
                        <div className={styles.info}>{stepsMap[currentStep]?.intro}</div>
                        <WhiteSpace />
                    </div>
                )}
                {renderStep}
            </div>
        </div>
    );

    return (
        <>
            <div className={styles.fakeItem} style={{ background: '#fff' }} />
            <EntryMetaTag />
            <div className={styles.blankPage}>
                <div className={styles.entryGuideCtr}>
                    <Spin spinning={loading}>
                        <div>
                            <div style={{ backgroundColor: '#fff' }} id="entryGuideAnchor">
                                <p className={styles.name}>{entryPersonnelData.employeeName} 你好！</p>
                                <h3 className={styles.title}>请根据指引完成入职准备</h3>
                                <Steps current={currentStep} direction="horizontal" className={styles.steps}>
                                    {stepsMap.map((item, index) => (
                                        <Step
                                            title={item.title}
                                            icon={
                                                currentStep > index ? (
                                                    <IconPro
                                                        type="iconsuccessMark"
                                                        style={{
                                                            color: '#ffa22d',
                                                            transform: 'scale(1.12)',
                                                            display: 'block'
                                                        }}
                                                    />
                                                ) : (
                                                    <IconPro
                                                        type={`iconStep${index + 1}_${
                                                            currentStep === index ? 'F' : 'O'
                                                        }`}
                                                    />
                                                )
                                            }
                                            key={item.title}
                                        />
                                    ))}
                                </Steps>
                            </div>
                            <div>
                                {stepsMap[currentStep]?.intro && (
                                    <>
                                        <div className={styles.info}>{stepsMap[currentStep]?.intro}</div>
                                        <WhiteSpace />
                                    </>
                                )}
                                {renderStep}
                            </div>
                        </div>
                        {/* **** */}
                        {copyDownDom()}
                        {/* **** */}
                        <div className={styles.stepBtnCtr}>{renderStepButton}</div>
                    </Spin>
                </div>
            </div>
        </>
    );
};
export default withRouter(createForm()(EntryGuideMobile));
